<template>
  <a-drawer
    title="新增预算"
    :visible="visible"
    placement="right"
    width="50%"
    :destroyOnClose="true"
    @close="handleCancel"
    :maskClosable="false"
    :get-container="false"
    :headerStyle="{ background: '#fff', position: 'absolute', width: '100%', height: '52px', zIndex: 30 }"
    :bodyStyle="{ padding: '0px', background: '#fff' }">
    <div class="content" style="margin-top:52px;width:100%;margin-bottom: 60px;padding: 20px;">
      <slot name="content">
        <a-form-model ref="ruleAddForm" :model="addForm" :rules="addRules">
          <a-form-model-item label="门店" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storeId">
            <a-select placeholder="请选择门店" v-model="addForm.storeId">
              <a-select-option :value="item.storeId" v-for="(item, index) in storesList" :key="index">{{
                item.storeName
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="预算标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title">
            <a-input placeholder="请输入预算标题" :max-length="100" v-model.trim="addForm.title" />
          </a-form-model-item>
          <a-form-model-item label="预算周期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="budgetType">
            <a-select placeholder="请选择预算周期" v-model="addForm.budgetType" @change="selectType">
              <a-select-option :value="item.id" v-for="(item, index) in typeList" :key="index">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item label="预算日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="budgetDate">
            <!--  :disabled-date="disabledDate"  -->
            <a-date-picker
              placeholder="请选择预算开始日期"
              v-model="addForm.budgetDate"
              :value-format="formatTime"
              style="width: 100%;"
            />
          </a-form-model-item>
          <a-form-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-textarea :rows="4" v-model.trim="addForm.description" placeholder="请输入描述信息" :max-length="255" />
          </a-form-item>
          <a-form-model-item :wrapper-col="{ offset: 5, span: 16 }">
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <!-- <a-button type="primary" @click="onExcel" v-show="headersSource.length > 0"
                            style="margin-left: 20px;">导出</a-button> -->
            <!-- <a-button type="primary" @click="handleSubmit" v-show="headersSource.length > 0"
                            style="margin-left: 20px;" :visible="visibleBtn" :loading="loadingBtn">保存</a-button> -->
          </a-form-model-item>
        </a-form-model>

      </slot>

    </div>
    <tableSaveModal ref="tableSaveModal" v-if="tableSave" @success="handleCancel" @close="handleCancel">
    </tableSaveModal>

    <tableSaveYearModal ref="tableSaveYearModal" v-if="tableSaveYear" @success="handleCancel" @close="handleCancel">
    </tableSaveYearModal>
  </a-drawer>
</template>

<script>
import { getBudgetsLaunch, addBudgets } from '@/api/budget'
import { exportExcelFinal } from '@/utils/exportExcel'
import { getStores } from '@/api/stores'

// 月度预算
import tableSaveModal from './tableSave'
// 年度预算
import tableSaveYearModal from './tableSaveYear'

import moment from 'moment'
export default {
    components: { tableSaveModal, tableSaveYearModal },
    data () {
        return {

            visible: false,
            confirmLoading: false,
            loading: false,
            visibleBtn: false,
            loadingBtn: false,
            addRules: {
                budgetDate: [
                    { required: true, message: '请选择预算开始日期!', trigger: 'change' }
                ],
                storeId: [
                    { required: true, message: '请选择门店!', trigger: 'change' }
                ],
                budgetType: [
                    { required: true, message: '请选择预算周期!', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请输入预算标题!', trigger: 'blur' }
                ]
            },
            addForm: {
                storeId: undefined,
                budgetType: undefined,
                budgetDate: '',
                title: '',
                description: ''
            },
            typeList: [
                { id: 1, name: '年度预算' },
                { id: 2, name: '月度预算' }
            ],

            //  表单样式
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },

            formatTime: 'YYYY-MM-DD',
            headersSource: [],
            dataSource: [],
            newdataSource: [],
            newArr: [], // 保存修改的id

            storesList: [],

            tableSave: false,
            tableSaveYear: false

        }
    },
    methods: {
        onExcel () {
            var handledata = []
            var cols = []
            this.headersSource.map((v, index) => {
                var a = []
                if (index != 0) {
                    a['title'] = v.name
                    a['dataIndex'] = index
                    cols.push(a)
                }
            })
            exportExcelFinal(cols, this.newdataSource)
        },
        disabledDate (current) {
            return current && current > moment().endOf('day')
        },
        // 计算比率
        // 本月比上月情况=（本月数字-上月数字）/上月数字，如果本月大于上月，结果就是正数，即上升，反之为下降
        rateCompute (a, b) {
            if (a > 0 || b > 0) {
                if (a > b) return Math.round(((b - a) / a) * 100) + '%'
                else if (b > a) return Math.round(((b - a) / b) * 100) + '%'
                else return '0%'
            } else {
                return '0%'
            }
        },
        // 获取填报改变的值
        handleChange (value, rowId, itId) {
            console.log(value, rowId, itId)
            if (value > 0) { // 01 = > 1
                if (value[0] == 0) {
                    value = value.substr(1)
                }
            } else if (value == 0) { // 00 => 0
                value = value.slice(0, 1)
            }
            // 从当前位置截取数组
            const parentArr = this.newdataSource.slice(rowId)
            // 满足条件的需要统计的下标
            let currentParentId = parentArr.findIndex((item) => item.datas[0] === '')
            // 当前统计的下标
            currentParentId = rowId + currentParentId
            // 上一个统计的下标
            const preArr = this.newdataSource.slice(0, rowId)
            const preParentId = preArr.findLastIndex((item) => item.datas[0] === '')
            this.newdataSource.forEach((item, index) => {
                if (index == rowId) {
                    item.datas.splice(itId, 1, value)
                    // 获取上个月和当前预算的数据，动态改变提升利率
                    const pre = item.datas[itId - 1]
                    const now = item.datas[itId]
                    item.datas.splice(itId + 1, 1, this.rateCompute(Number(pre), Number(now)))
                    if (item.datas[0] != '') this.newArr.push(item.datas[0])
                    this.newArr = Array.from(new Set(this.newArr))
                }
            })
            let total = 0
            this.newdataSource.forEach((item, index) => {
                if (index > preParentId && index <= currentParentId - 1) {
                    total += Number(item.datas[itId])
                }
            })
            this.newdataSource.forEach((item, index) => {
                if (index == currentParentId) {
                    item.datas.splice(itId, 1, total)
                    // 获取上个月和当前预算的数据，动态改变提升利率
                    const pre = item.datas[itId - 1]
                    const now = item.datas[itId]
                    item.datas.splice(itId + 1, 1, this.rateCompute(Number(pre), Number(now)))
                }
            })
        },
        selectType (value) {
            if (value == 1) this.formatTime = 'YYYY'
            else this.formatTime = 'YYYY-MM-DD'
        },
        // 显示
        open () {
            this.visible = true
            getStores({ storeName: '' }).then(res => {
                if (res.code == 200) {
                    this.storesList = res.data
                    // this.pagination.total = res.data.total
                }
            })
            return this
        },

        // 关闭
        handleCancel () {
            this.visible = false
            this.loadingBtn = false
            this.visibleBtn = false

            this.tableSave = false,
            this.tableSaveYear = false
            this.$emit('close')
            this.$emit('success')
        },
        // 确认
        handleSubmit () {
            // 获取项目id 的下标
            const projectId = (this.headersSource || []).findIndex((item) => item.columnId === 'projectId')
            const filterArr = this.newdataSource.filter(item => {
                return this.newArr.includes(item.datas[projectId])
            })
            // 获取需要填报的下标
            const budgetAmountId = (this.headersSource || []).findIndex((item) => item.primary === true)
            let objectArr = []
            objectArr = filterArr.map(item => {
                const obj = {}
                if (item.datas[budgetAmountId] > 0) {
                    // 获取项目id和项目值
                    obj.projectId = item.datas[projectId]
                    obj.budgetAmount = item.datas[budgetAmountId]
                    return obj
                } else {
                    return ''
                }
            }).filter(item => item)
            if (objectArr.length == 0) {
                this.$notification['error']({
                    message: '提示',
                    description: '请编辑预算项目',
                    duration: 8
                })
                return
            }
            this.loadingBtn = true
            this.visibleBtn = true
            this.$refs.ruleAddForm.validate(valid => {
                if (valid) {
                    const { budgetType, budgetDate, description, title, storeId } = this.addForm
                    const par = {
                        budgetType,
                        budgetDate,
                        projects: objectArr,
                        description,
                        title,
                        storeId
                    }
                    addBudgets(par).then(res => {
                        if (res.code === 200) {
                            this.$notification['success']({
                                message: '提示',
                                description: '保存成功！',
                                duration: 8
                            })
                            this.visible = false
                            this.$emit('success')
                        } else {
                            this.$notification['error']({
                                message: '提示',
                                description: res.message,
                                duration: 8
                            })
                        }
                        this.visibleBtn = false
                        this.loadingBtn = false
                    })
                } else {
                    this.loadingBtn = false
                    this.visibleBtn = false
                    return false
                }
            })
        },
        // 搜索
        handleSearch () {
            // this.tableSaveYear = true
            // let { storeId, budgetType, budgetDate, title, description } = this.addForm
            // let par = {
            //     storeId,
            //     budgetType,
            //     budgetDate: budgetType == 1 ? budgetDate + '-01-01' : budgetDate,
            //     title,
            //     description
            // }
            // this.$nextTick(() => {
            //     this.$refs.tableSaveYearModal.open('add', par)
            // })

            this.$refs.ruleAddForm.validate(valid => {
                if (valid) {
                    if (this.addForm.budgetType == 1) {
                        const { storeId, budgetType, budgetDate, title, description } = this.addForm
                        const par = {
                            storeId,
                            budgetType,
                            budgetDate: budgetType == 1 ? budgetDate + '-01-01' : budgetDate,
                            title,
                            description
                        }
                        this.tableSaveYear = true
                        this.$nextTick(() => {
                            this.$refs.tableSaveYearModal.open('add', par)
                        })
                    } else {
                        this.tableSave = true
                        this.$nextTick(() => {
                            this.$refs.tableSaveModal.open('add', this.addForm)
                        })
                    }

                    // getBudgetsLaunch(par).then(res => {
                    //     console.log(res)
                    //     if (res.code == 200) {
                    //         this.headersSource = []
                    //         this.dataSource = res.data.lines
                    //         let lines = res.data.lines
                    //         this.headersSource = res.data.headers
                    //         // this.headersSource.push({
                    //         //     "columnId": "",
                    //         //     "name": "提升比率",
                    //         //     "hidden": false,
                    //         //     "primary": false
                    //         // })
                    //         // // 获取填报的下标
                    //         // let budgetAmountId = (this.headersSource || []).findIndex((item) => item.primary === true);
                    //         // this.newdataSource = lines.map((item, index) => {
                    //         //     if (index == budgetAmountId) {
                    //         //         // 根据填报位置，获取上一个月份的信息
                    //         //         let pre = item.datas[index - 1]
                    //         //         let now = item.datas[budgetAmountId]
                    //         //         item.datas.push(this.rateCompute(Number(pre), Number(now)))
                    //         //     } else {
                    //         //         item.datas.push('0%')
                    //         //     }
                    //         //     let obj = {
                    //         //         ...item
                    //         //     }
                    //         //     return obj
                    //         // })
                    //     } else {
                    //         this.$notification['error']({
                    //             message: '提示',
                    //             description: res.message,
                    //             duration: 8
                    //         })
                    //     }
                    //     this.loading = false
                    // })
                } else {

                }
            })
        }
    }
}
</script>
<style scoped>
.ant-input-disabled,
.ant-input-number-disabled {
    color: rgba(0, 0, 0, 0.65) !important;
    background: #fcfcfc !important;
    cursor: not-allowed !important;
}

.vtable {
    width: 100%;
    height: 600px;
    /* height: 400px;
    overflow-y: auto;
    overflow-x: hidden; */
}

.thead-th {
    width: 100%;
    padding: 10px;

}

.row-td {
    width: 100%;
    height: 100%;
    padding: 10px;
    border: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    /* margin: -5px 0; */
    flex: 1;
}
</style>
